package com.zhiyun.hxzy.util;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

@Component
public class UploadUtil {
    private static String localPath;
    public static String getLocalPath() {
        return localPath;
    }

    @Value("${localPath}")
    public void setLocalPath(String localPath) {
        UploadUtil.localPath = localPath;
    }

    private String uploadToService(MultipartFile file, String fileName) {
        Client client = Client.create();
        String path = localPath + fileName;
        WebResource resource = client.resource(path);
        try {
            resource.put(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public String upload(MultipartFile file){
        //获取文件名
        String fileName = file.getOriginalFilename();
        try {
            fileName = URLEncoder.encode(fileName,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        fileName = UUID.randomUUID() + fileName;
        String path = uploadToService(file, fileName);
        return path;
    }
}
